package com.whl.sm.service.impl.system;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.whl.sm.mapper.system.SysMenuMapper;
import com.whl.sm.model.system.SysMenu;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.service.system.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-09-10
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private OrgUserService orgUserService;

    @Override
    public List<SysMenu> getMenuTree() {
        List<SysMenu> menuList = getBaseMapper().selectList(new QueryWrapper<SysMenu>().orderByDesc("create_time"));
        return buildTreeMenu(menuList);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public int update(SysMenu sysMenu) {
        sysMenu.setOperator(orgUserService.getCurrentUserId());
        if (StringUtils.isNotBlank(sysMenu.getId())){
            getBaseMapper().updateById(sysMenu);
        }
        else {
            if (sysMenu.getParentId()==null){
                sysMenu.setParentId("0");
            }
            List<SysMenu> typeList = getBaseMapper().selectList(new QueryWrapper<SysMenu>()
                    .eq("parent_id",sysMenu.getParentId())
                    .orderByDesc("create_time")
            );
            int insertOrderNum = 1;
            if (typeList.size()>0){
                insertOrderNum = typeList.get(0).getOrderNum()+1;
            }
            sysMenu.setOrderNum(insertOrderNum);
            this.getBaseMapper().insert(sysMenu);
        }
        return 0;
    }


    private List<SysMenu> buildTreeMenu(List<SysMenu> menus) {
        List<SysMenu> finalMenus = new ArrayList<>();
        for (SysMenu menu : menus) {               // 先寻找各自的孩子
            for (SysMenu e : menus) {
                if (e.getParentId().equals(menu.getId())) {
                    menu.getChildren().add(e);
                }
            }         // 提取出父节点
            if (menu.getParentId().equals("0")) {
                finalMenus.add(menu);
            }
        }
        return finalMenus;
    }

}
